/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.stdlib;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Fail;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;

/**
 * Implements all primitives from 'weak.c'.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Weak {

    /** <i>None</i> value. */
    private static final Value NONE = Value.ZERO;

    /** Tag for <i>Some x</i> value. */
    private static final int SOME_TAG = 0;

    /**
     * No instance of this class.
     */
    private Weak() {
    } // end empty constructor

    /**
     * Creates a block/array of weak values.
     * @param ctxt context
     * @param len length of block/array
     * @return block/array of <tt>len</tt> weak values,
     *         all values are set to <i>None</i>
     * @throws Fail.Exception if length is invalid
     */
    @Primitive
    public static Value caml_weak_create(final CodeRunner ctxt,
                                         final Value len)
        throws Fail.Exception {
        final int sz = len.asLong() + 1;
        if ((sz <= 0) || (sz > Block.MAX_WOSIZE)) {
            Fail.invalidArgument("Weak.create");
        } // end if
        return Value.createFromBlock(Block.createWeakBlock(sz));
    } // end method 'caml_weak_create(CodeRunner, Value)'

    /**
     * Sets the value of a block/array of weak values.
     * @param ctxt context
     * @param ar block/array of weak values
     * @param n index of value to return
     * @param el new value (can be <i>None</i> or <i>Some x</i>)
     * @return <i>unit</i>
     * @throws Fail.Exception if index is invalid
     */
    @Primitive
    public static Value caml_weak_set(final CodeRunner ctxt,
                                      final Value ar,
                                      final Value n,
                                      final Value el)
        throws Fail.Exception {
        final Block block = ar.asBlock();
        final int offset = n.asLong() + 1;
        if ((offset < 1) || (offset >= block.getWoSize())) {
            Fail.invalidArgument("Weak.set");
        } else {
            block.setWeak(offset, null);
            if (el.isBlock()) {
                assert el.asBlock().getWoSize() == 1 : "invalid el";
                block.setWeak(offset, el.asBlock().get(0));
            } // end if
        } // end if/else
        return Value.UNIT;
    } // end method 'caml_weak_set(CodeRunner, Value, Value, Value)'

    /**
     * Returns a value from a block/array of weak values.
     * @param ctxt context
     * @param ar block/array of weak values
     * @param n index of value to return
     * @return <i>None</i> if the weak value at that index is not set,
     *         <i>Some x</i> if the weak value at that index is <i>x</i>
     * @throws Fail.Exception if index is invalid
     */
    @Primitive
    public static Value caml_weak_get(final CodeRunner ctxt,
                                      final Value ar,
                                      final Value n)
        throws Fail.Exception {
        final Block block = ar.asBlock();
        final int offset = n.asLong() + 1;
        if ((offset < 1) || (offset >= block.getWoSize())) {
            Fail.invalidArgument("Weak.get");
        } // end if
        final Value elem = block.getWeak(offset);
        if (elem == null) {
            return Weak.NONE;
        } else {
            final Block res = Block.createBlock(Weak.SOME_TAG, elem);
            return Value.createFromBlock(res);
        } // end if/else
    } // end method 'caml_weak_get(CodeRunner, Value, Value)'

    /**
     * Returns acopy of a value from a block/array of weak values.
     * @param ctxt context
     * @param ar block/array of weak values
     * @param n index of value to return
     * @return <i>None</i> if the weak value at that index is not set,
     *         <i>Some x2</i> if the weak value at that index is <i>x</i>,
     *         <i>x2</i> being a copy of <i>x</i>
     * @throws Fail.Exception if index is invalid
     */
    @Primitive
    public static Value caml_weak_get_copy(final CodeRunner ctxt,
                                           final Value ar,
                                           final Value n)
        throws Fail.Exception {
        final Block block = ar.asBlock();
        final int offset = n.asLong() + 1;
        if ((offset < 1) || (offset >= block.getWoSize())) {
            Fail.invalidArgument("Weak.get");
        } // end if
        final Value v = block.getWeak(offset);
        if (v == null) {
            return Weak.NONE;
        } else {
            final Value elem;
            if (v.isBlock()) {
                final Block bl = v.asBlock();
                final int sz = bl.getWoSize();
                final int tag = bl.getTag();
                final Block tmp = Block.createBlock(sz, tag);
                if (tag < Block.NO_SCAN_TAG) {
                    for (int i = 0; i < sz; i++) {
                        tmp.set(i, bl.get(i));
                    } // end for
                    elem = Value.createFromBlock(tmp);
                } else {
                    elem = Value.createFromBlock(bl.duplicate());
                } // end if/else
            } else {
                elem = v;
            } // end if/else
            final Block b = Block.createBlock(Weak.SOME_TAG, elem);
            return Value.createFromBlock(b);
        } // end if/else
    } // end method 'caml_weak_get_copy(CodeRunner, Value, Value)'

    /**
     * Checks whether a weak value from a block/array is set or not.
     * @param ctxt context
     * @param ar block/array
     * @param n index
     * @return {@link fr.x9c.cadmium.kernel.Value#TRUE} if the element of
     *         <tt>ar</tt> at index <tt>n</tt> is set,
     *         {@link fr.x9c.cadmium.kernel.Value#FALSE} otherwise
     * @throws Fail.Exception if index is invalid
     */
    @Primitive
    public static Value caml_weak_check(final CodeRunner ctxt,
                                        final Value ar,
                                        final Value n)
        throws Fail.Exception {
        final Block block = ar.asBlock();
        final int offset = n.asLong() + 1;
        if ((offset < 1) || (offset >= block.getWoSize())) {
            Fail.invalidArgument("Weak.get");
        } // end if
        return block.getWeak(offset) != null ? Value.TRUE : Value.FALSE;
    } // end method 'caml_weak_check(CodeRunner, Value, Value)'

    @Primitive
    public static Value caml_weak_blit(final CodeRunner ctxt,
                                       final Value ars,
                                       final Value ofs,
                                       final Value ard,
                                       final Value ofd,
                                       final Value len)
        throws Fail.Exception {
        final Block blockS = ars.asBlock();
        final Block blockD = ard.asBlock();
        final int offsetS = ofs.asLong() + 1;
        final int offsetD = ofd.asLong() + 1;
        final int length = len.asLong();
        if ((offsetS < 1) || (offsetS + length > blockS.getWoSize())) {
            Fail.invalidArgument("Weak.blit");
        } // end if
        if ((offsetD < 1) || (offsetD + length > blockD.getWoSize())) {
            Fail.invalidArgument("Weak.blit");
        } // end if
        if (offsetD < offsetS) {
            for (int i = 0; i < length; i++) {
                blockD.setWeak(offsetD + i, blockS.getWeak(offsetS + i));
            } // end for
        } else {
            for (int i = length - 1; i >= 0; i--) {
                blockD.setWeak(offsetD + i, blockS.getWeak(offsetS + i));
            } // end for
        } // end if/else
        return Value.UNIT;
    } // end method 'caml_weak_blit(CodeRunner, Value, Value, Value, Value, Value)'

} // end class 'Weak'
